package com.substation.ui.activity;

import android.content.Intent;
import android.support.v7.widget.RecyclerView;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.greenentity.Eqpt;
import com.greenentity.Photo;
import com.greenentity.Substation;
import com.greenentity.TourDefect;
import com.jessewu.library.SuperAdapter;
import com.jessewu.library.view.ViewHolder;
import com.net.SubstationNet;
import com.previewlibrary.ZoomMediaLoader;
import com.substation.R;
import com.substation.greendao.EqptDao;
import com.substation.greendao.PhotoDao;
import com.substation.greendao.SubstationDao;
import com.substation.greendao.TourDefectDao;
import com.substation.ui.adapter.DefectImageAdapter;
import com.substation.ui.utils.MyImageLoader;
import com.substation.ui.utils.RecyclerViewUtils;
import com.substation.utils.GreenDaoManager;
import com.substation.utils.SPUtils;
import com.substation.utils.T;
import com.substation.utils.ZipUtils;

import java.util.ArrayList;
import java.util.List;

/**
 * 缺陷管理
 */
public class DefectActivity extends BaseListActivity {

    SuperAdapter<TourDefect> adapter;
    List<TourDefect> datas = new ArrayList<>();
    TourDefect td;//上传的缺陷

    @Override
    protected void initView() {
        super.initView();
        ZoomMediaLoader.getInstance().init(new MyImageLoader());
        adapter.setData(datas);
        adapter.setEmptyDataView(R.layout.view_empty);
        refresh.setEnabled(false);
    }

    @Override
    protected void initData() {
        datas.clear();
        datas.addAll(GreenDaoManager.getInstance().getmDaoSession().getTourDefectDao().queryBuilder().orderDesc(TourDefectDao.Properties.SubsGuid,TourDefectDao.Properties.DefectTime).list());
        adapter.notifyDataSetChanged();
    }

    @Override
    public SuperAdapter getAdapter() {
        return adapter = new SuperAdapter<TourDefect>(R.layout.content_defect) {
            @Override
            public void bindView(ViewHolder viewHolder, final TourDefect tourDefect, int i) {
                List<Substation> substations = GreenDaoManager.getInstance().getmDaoSession().getSubstationDao().queryBuilder()
                        .where(SubstationDao.Properties.Guid.eq(tourDefect.getSubsGuid())).list();
                final String sub = substations.size() > 0 ? substations.get(0).getNames() : "未知变电站";
                ((TextView) viewHolder.getView(R.id.substation)).setText(sub);
                ((TextView) viewHolder.getView(R.id.lv)).setText("(" + tourDefect.getDefectLevelvalue() + ")");
                ((TextView) viewHolder.getView(R.id.description)).setText(tourDefect.getDefectDesc());
                List<Eqpt> eqpts = GreenDaoManager.getInstance().getmDaoSession().getEqptDao().queryBuilder()
                        .where(EqptDao.Properties.EqptGuid.eq(tourDefect.getEqptGuid())).list();
                ((TextView) viewHolder.getView(R.id.eqpt)).setText(eqpts.size() > 0 ? eqpts.get(0).getEqptName() : "未知设备");
                ((TextView) viewHolder.getView(R.id.finds)).setText(tourDefect.getDiscoveryUserIdvalue());
                ((TextView) viewHolder.getView(R.id.time)).setText(tourDefect.getDefectTime());
                Button process = viewHolder.getView(R.id.process);
                RecyclerView recyclerView = viewHolder.getView(R.id.list);
                recyclerView.setLayoutManager(RecyclerViewUtils.getLinearLayoutManagerForHorizontal(context));
                List<Photo> photos = GreenDaoManager.getInstance().getmDaoSession().getPhotoDao().queryBuilder()
                        .where(PhotoDao.Properties.DefectGuid.eq(tourDefect.getDefectGuid())).list();
                SuperAdapter<Photo> adapter = new DefectImageAdapter(DefectActivity.this, photos);
                recyclerView.setAdapter(adapter);
                adapter.setData(photos);
                adapter.setEmptyDataView(R.layout.view_empty);
                if (tourDefect.getDefectStatus().equals("20")) {
                    process.setText("上传");
                    process.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            List<Photo> newPhotos = GreenDaoManager.getInstance().getmDaoSession().getPhotoDao().queryBuilder()
                                    .where(PhotoDao.Properties.DefectGuid.eq(tourDefect.getDefectGuid()), PhotoDao.Properties.PhState.eq("新增")).list();
                            td = tourDefect;
                            if (ZipUtils.zip(newPhotos))
                                SubstationNet.uploadTourDefect(context, tourDefect, newPhotos, DefectActivity.this);
                        }
                    });
                } else {
                    process.setText("消缺");
                    process.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            SPUtils.put(context, "work", false);//是否是从巡视任务过来的
                            SPUtils.put(context, "defect", JSON.toJSONString(tourDefect));
                            SPUtils.put(context, "substations", sub);
                            startActivity(new Intent(context, RemoveDefectActivity.class));
                        }
                    });
                }
            }
        };
    }

    @Override
    public void success(int i, String obj) {
        switch (i) {
            case 1:
                JSONObject jsonObject = JSON.parseObject(obj);
                String tourdefects = jsonObject.getString("tourdefects");
                String tourdefectphotoList = jsonObject.getString("tourdefectphotoList");
                List<TourDefect> tourDefects = JSON.parseArray(tourdefects, TourDefect.class);
                List<Photo> photos = JSON.parseArray(tourdefectphotoList, Photo.class);
                List<String> guid = new ArrayList<>();
                for (TourDefect t : tourDefects) {
                    guid.add(t.getDefectGuid());
                    if (GreenDaoManager.getInstance().getmDaoSession().getTourDefectDao().queryBuilder()
                            .where(TourDefectDao.Properties.DefectGuid.eq(t.getDefectGuid())).count() == 0) {
                        GreenDaoManager.getInstance().getmDaoSession().getTourDefectDao().insert(t);
                    }
                }
                GreenDaoManager.getInstance().getmDaoSession().getTourDefectDao().queryBuilder()
                        .where(TourDefectDao.Properties.DefectGuid.notIn(guid))
                        .buildDelete().executeDeleteWithoutDetachingEntities();//删除服务器已经消缺的数据
                for (Photo p : photos) {
                    if (GreenDaoManager.getInstance().getmDaoSession().getPhotoDao().queryBuilder().where(PhotoDao.Properties.PhotoGuid.eq(p.getPhotoGuid())).count() == 0) {
                        GreenDaoManager.getInstance().getmDaoSession().getPhotoDao().insert(p);
                    } else {
                        Photo photo = GreenDaoManager.getInstance().getmDaoSession().getPhotoDao().queryBuilder().where(PhotoDao.Properties.PhotoGuid.eq(p.getPhotoGuid())).list().get(0);
                        photo.setPhUrl(p.getPhUrl());
                        GreenDaoManager.getInstance().getmDaoSession().getPhotoDao().update(photo);
                    }
                }
                datas.clear();
                datas.addAll(GreenDaoManager.getInstance().getNewSession().getTourDefectDao().queryBuilder().orderDesc(TourDefectDao.Properties.SubsGuid,TourDefectDao.Properties.DefectTime).list());
                adapter.notifyDataSetChanged();
                break;
            case 2:
                T.showLong(context, obj);
                GreenDaoManager.getInstance().getNewSession().getTourDefectDao().delete(td);
                datas.remove(td);
                adapter.notifyDataSetChanged();
                break;
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_refer, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.refer:
                SubstationNet.getTourDefect(context, this);
                return true;
        }
        return super.onOptionsItemSelected(item);
    }
}
